package com.toman.ui.work.base;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Adpter.ItemListAdapter;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.R;
import com.toman.Util.JsonUtils;
import com.toman.Util.TimeUtil;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.ItemListBean;
import com.toman.toolbar.ToolBarActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;

public class ShiftAddActivity extends ToolBarActivity {

    @BindView(R.id.et_name)
    EditText etName;

    PopupWindow popupWindow;
    String start_time;
    String end_time;
    int HourOfDay;
    int Minute;
    @BindView(R.id.btn_save)
    Button btnSave;
    @BindView(R.id.et_no)
    EditText etNo;
    @BindView(R.id.tv_time_start)
    TextView tvTimeStart;
    @BindView(R.id.rl_time_start)
    RelativeLayout rlTimeStart;
    @BindView(R.id.tv_time_end)
    TextView tvTimeEnd;
    @BindView(R.id.rl_time_end)
    RelativeLayout rlTimeEnd;
    @BindView(R.id.tv_dep)
    TextView tvDep;
    @BindView(R.id.rl_dep)
    RelativeLayout rlDep;
    ItemListAdapter adapter;
    List<ItemListBean> list = new ArrayList<ItemListBean>();
    String depId;
    ListView lv;
    @BindView(R.id.tv_dep_name)
    TextView tvDepName;
    @BindView(R.id.tv_day_name)
    TextView tvDayName;
    @BindView(R.id.tv_day)
    TextView tvDay;
    @BindView(R.id.rl_day)
    RelativeLayout rlDay;
    @BindView(R.id.tv_tally_start)
    TextView tvTallyStart;
    @BindView(R.id.rl_tally_start)
    RelativeLayout rlTallyStart;
    @BindView(R.id.tv_tally_end)
    TextView tvTallyEnd;
    @BindView(R.id.rl_tally_end)
    RelativeLayout rlTallyEnd;
    private String isToday = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shift_add);
        ButterKnife.bind(this);
        initView();

    }

    private void initView() {
        adapter = new ItemListAdapter(this, 2);

        if (getIntent().getStringExtra("type").equals("1")) {
            depId = getIntent().getStringExtra("d_id");
            tvDep.setText(getIntent().getStringExtra("dep_name"));
            initToolBar("新增班次");
        }
        if (getIntent().getStringExtra("type").equals("2")) {
            initToolBar("编辑班次");
            etName.setText(getIntent().getStringExtra("name"));
            start_time = getIntent().getStringExtra("start_time");
            end_time = getIntent().getStringExtra("end_time");
            etNo.setText(getIntent().getStringExtra("shiftNum"));
            tvDep.setText(getIntent().getStringExtra("dep_name"));
            depId = getIntent().getStringExtra("dep_id");
            if (getIntent().getStringExtra("isToday").equals("0")) {
                isToday = "0";
                tvDay.setText("否");
            } else {
                isToday = "1";
                tvDay.setText("是");
            }
            tvTimeStart.setText(start_time);
            tvTimeEnd.setText(end_time);
            tvTallyStart.setText(getIntent().getStringExtra("deviceCheckStartTime"));
            tvTallyEnd.setText(getIntent().getStringExtra("deviceCheckEndTime"));

        }
    }


    public void add() {
        if (etName.getText().toString().length() < 1) {
            ToastUtil.makeText(getApplicationContext(), "请输入班次名称");
            return;
        }
        if (etNo.getText().toString().length() < 1) {
            ToastUtil.makeText(getApplicationContext(), "请输入班次编号");
            return;
        }
        if (tvTimeStart.getText().toString().length() < 1) {
            ToastUtil.makeText(getApplicationContext(), "请输入开始时间");
            return;
        }
        if (tvTimeEnd.getText().toString().length() < 1) {
            ToastUtil.makeText(getApplicationContext(), "请输入结束时间");
            return;
        }
        if (isToday.equals("0")) {
            if (!TimeUtil.compareTwoTimeHour(tvTimeStart.getText().toString(), tvTimeEnd.getText().toString())) {
                ToastUtil.makeText(getApplicationContext(), "结束时间必须晚于开始时间");
                return;
            }
        }
if (((tvTallyStart.getText().toString().length()>0)&&(tvTallyEnd.getText().toString().length()<1))||((tvTallyEnd.getText().toString().length()>0)&&(tvTallyStart.getText().toString().length()<1))){
                ToastUtil.makeText(getApplicationContext(), "点检开始结束时间必须成对出现");
                return;
            }
            if (tvTallyStart.getText().toString().length()>0){
                if (!TimeUtil.compareTwoTimeHour(tvTallyStart.getText().toString(), tvTallyEnd.getText().toString())) {
                    ToastUtil.makeText(getApplicationContext(), "点检结束时间必须晚于点检开始时间");
                    return;
                }
            }
        if (!TimeUtil.compareTwoTimeHour(tvTallyEnd.getText().toString(), tvTimeEnd.getText().toString())) {
            ToastUtil.makeText(getApplicationContext(), "点检结束时间必须晚于班次结束时间");
            return;
        }



        Map<String, String> map = new HashMap<String, String>();
        map.put("shiftName", etName.getText().toString());
        map.put("companyId", companyId);
        map.put("departmentId", depId);
        map.put("startTime", tvTimeStart.getText().toString());
        map.put("endTime", tvTimeEnd.getText().toString());
        map.put("shiftNum", etNo.getText().toString());
        map.put("isToday", isToday);
        map.put("deviceCheckStartTime", tvTallyStart.getText().toString());
        map.put("deviceCheckEndTime", tvTallyEnd.getText().toString());


        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.shift_save_post)
                .headers("token", token)
                .headers("Content-Type", "application/json")
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "新增班次: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });

    }


    private void save() {
        switch (getIntent().getStringExtra("type")) {
            case "1":
                add();
                break;

            case "2":
                edit();
                break;
        }
    }

    private void edit() {
        if (etName.getText().toString().length() < 1) {
            ToastUtil.makeText(getApplicationContext(), "请输入班次名称");
            return;
        }
        if (etNo.getText().toString().length() < 1) {
            ToastUtil.makeText(getApplicationContext(), "请输入班次编号");
            return;
        }
        if (tvTimeStart.getText().toString().length() < 1) {
            ToastUtil.makeText(getApplicationContext(), "请输入开始时间");
            return;
        }
        if (tvTimeEnd.getText().toString().length() < 1) {
            ToastUtil.makeText(getApplicationContext(), "请输入结束时间");
            return;
        }
        if (isToday.equals("0")) {
            if (!TimeUtil.compareTwoTimeHour(tvTimeStart.getText().toString(), tvTimeEnd.getText().toString())) {
                ToastUtil.makeText(getApplicationContext(), "结束时间必须晚于开始时间");
                return;
            }
        }
        if (((tvTallyStart.getText().toString().length()>0)&&(tvTallyEnd.getText().toString().length()<1))||((tvTallyEnd.getText().toString().length()>0)&&(tvTallyStart.getText().toString().length()<1))){
            ToastUtil.makeText(getApplicationContext(), "点检开始结束时间必须成对出现");
            return;
        }
        if (tvTallyStart.getText().toString().length()>0){
            if (!TimeUtil.compareTwoTimeHour(tvTallyStart.getText().toString(), tvTallyEnd.getText().toString())) {
                ToastUtil.makeText(getApplicationContext(), "点检结束时间必须晚于点检开始时间");
                return;
            }
        }
        if (!TimeUtil.compareTwoTimeHour(tvTallyEnd.getText().toString(), tvTimeEnd.getText().toString())) {
            ToastUtil.makeText(getApplicationContext(), "点检结束时间必须晚于班次结束时间");
            return;
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("shiftName", etName.getText().toString());
        map.put("departmentId", depId);
        map.put("companyId", companyId);
        map.put("startTime", tvTimeStart.getText().toString());
        map.put("endTime", tvTimeEnd.getText().toString());
        map.put("shiftNum", etNo.getText().toString());
        map.put("id", getIntent().getStringExtra("id"));
        map.put("isToday", isToday);
        map.put("deviceCheckStartTime", tvTallyStart.getText().toString());
        map.put("deviceCheckEndTime", tvTallyEnd.getText().toString());
        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.shift_update_post)
                .headers("token", token)
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "新增班次: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    public void dilogDep() {
        final AlertDialog dialog;
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater factory = LayoutInflater.from(this);
        //把activity_login中的控件定义在View中
        final View textEntryView = factory.inflate(R.layout.dialog_list, null);
        lv = (ListView) textEntryView.findViewById(R.id.lv);
        lv.setAdapter(adapter);
        lv.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);

        builder                //对话框的标题
                .setTitle("选择部门")
                //设定显示的View
                .setView(textEntryView)
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        SparseBooleanArray array;
                        array = lv.getCheckedItemPositions();
                        StringBuilder name = new StringBuilder();
                        StringBuilder id = new StringBuilder();

                        for (int j = 0; j < array.size(); j++) {
                            ItemListBean bean = adapter.getItem(j);

                            if (array.get(j)) {
                                if (name.length() <= 0) {
                                    name.append(bean.getName());
                                    id.append(bean.getID());

                                } else {
                                    name.append(",").append(bean.getName());
                                    id.append(",").append(bean.getID());
                                }

                            }
                        }
                        if (name.length() <= 0) {
                            ToastUtil.makeText(getApplicationContext(), "至少选中一个部门");
                            return;
                        } else {
                            tvDep.setText(name.toString());
                            depId = id.toString();
                        }

                    }
                })
                //对话框的“退出”单击事件
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create();
        dialog = builder.show();
        dep();
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
        });

    }

    public void dep() {

        OkHttpUtils
                .get(NewBaseUrl.department_list_get)
                .params("token", token)
                .params("companyId", companyId)
                .params("key", "")
                .params("limit", "1000")
                .params("page", "1")
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "部门列表: " + result);

                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());
                        if (code == 0) {
                            list.clear();
                            JSONObject Jpage = jsonObj.getJSONObject("page");
                            JSONArray jsonArray = Jpage.getJSONArray("list");
                            String ids[] = depId.split(",");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                ItemListBean bean = new ItemListBean(jsonArray.getJSONObject(i).getString("departmentName"), jsonArray.getJSONObject(i).getString("id"));
                                list.add(bean);
                                if (ids.length != 0) {
                                    for (int j = 0; j < ids.length; j++) {
                                        if (ids[j].equals(bean.getID())) {
                                            lv.setItemChecked(i, true);
                                            break;
                                        } else {
                                            lv.setItemChecked(i, false);
                                        }
                                    }
                                } else {
                                    lv.setItemChecked(i, false);
                                }
                            }
                            adapter.refreshData(list);

                            adapter.notifyDataSetChanged();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }


    @OnClick({R.id.rl_time_start, R.id.rl_time_end, R.id.rl_dep, R.id.btn_save, R.id.rl_day,R.id.rl_tally_start, R.id.rl_tally_end})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_time_start:
                ViewUtil.getTime(this, tvTimeStart);

                break;
            case R.id.rl_time_end:
                ViewUtil.getTime(this, tvTimeEnd);

                break;
            case R.id.rl_tally_start:
                ViewUtil.getTime(this, tvTallyStart);

                break;
            case R.id.rl_tally_end:
                ViewUtil.getTime(this, tvTallyEnd);

                break;
            case R.id.rl_dep:
                dilogDep();
                break;

            case R.id.btn_save:
                save();
                break;

            case R.id.rl_day:
                if (isToday.equals("1")) {
                    tvDay.setText("否");
                    isToday = "0";
                } else if (isToday.equals("0")) {
                    tvDay.setText("是");
                    isToday = "1";
                }
                break;
        }
    }
}
